using UnityEngine;
using QFramework;
using System.Collections.Generic;

namespace ProjectSurviver
{
	/// <summary>
	/// 围绕主角旋转
	/// </summary>
	public partial class RotateSword : ViewController
	{
		List<Collider2D> mSwords = new List<Collider2D>();

		void Start()
		{
			Sword.Hide();

			void CreatSword()
			{
				mSwords.Add(Sword.InstantiateWithParent(this)
					.Self(self =>
					{
						self.OnTriggerEnter2DEvent(collider =>
						{
							var hurtBox = collider.GetComponent<HitHurtBox>();
							if(hurtBox)
							{
								if(hurtBox.Owner.CompareTag("Enemy"))
								{
									var damageTimes = Global.SuperRotateSword.Value ? Random.Range(2, 3 + 1) : 1; // 超级剑的话，伤害翻倍
									
									DamageSystem.CalculateDamage(Global.RotateSwordDamage.Value * damageTimes, hurtBox.Owner.GetComponent<Enemy>()); // 计算伤害
									
									if(Random.Range(0, 1.0f) < 0.5f)
									{
										collider.attachedRigidbody.velocity = 
										collider.NormalizedDirection2DFrom(self) * 5 +  // 给敌人一个击飞效果
										collider.NormalizedDirection2DFrom(Player.Default) * 10; // 给敌人一个击飞效果
									}
								}
							}
						}).UnRegisterWhenGameObjectDestroyed(self);
					})
					.Show());
			}

			void CreatSwords()
			{
				var toAddCount = Global.RotateSwordCount.Value + Global.AdditionFlyThingCount.Value - mSwords.Count; // 计算需要增加的剑的数量
				for (int i = 0; i < toAddCount; i++)
				{
					CreatSword(); // 创建剑
				}
				UpdateCirclePos(); // 更新剑的位置
			}
			Global.RotateSwordCount.Or(Global.AdditionFlyThingCount).Register(() =>
			{
				CreatSwords(); // 当剑的数量发生变化时，重新创建剑
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			Global.RotateSwordRange.Register(range =>
			{
				UpdateCirclePos();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			CreatSwords();
		}

        void Update()
        {
			var speed = Global.SuperRotateSword.Value 
			? Time.frameCount * 10 
			: Global.RotateSwordCount.Value * Time.frameCount; // 超级剑的话，速度翻倍

			this.LocalEulerAnglesZ(-speed);
        }

		void UpdateCirclePos()
		{
			var radius = Global.RotateSwordRange.Value; // 半径
			var durationDegrees = 360 / mSwords.Count;	// 每个剑的角度
			
			for (int i = 0; i < mSwords.Count; i++)
			{
				var circleLocalPos = new Vector2(Mathf.Cos(durationDegrees * i * Mathf.Deg2Rad), Mathf.Sin(durationDegrees * i * Mathf.Deg2Rad)) * radius; // 计算剑的位置
				mSwords[i].LocalPosition(circleLocalPos.x, circleLocalPos.y)
				.LocalEulerAnglesZ(durationDegrees * i -90); // 计算剑的角度
			}
		}
    }
}
